#include "BasicBlock.h"
#include "Constant.h"
#include "Function.h"
#include "IRBuilder.h"
#include "Module.h"
#include "Type.h"
 
#include <iostream>
#include <memory>
 
#ifdef DEBUG  // 用于调试信息,大家可以在编译过程中通过" -DDEBUG"来开启这一选项
#define DEBUG_OUTPUT std::cout << __LINE__ << std::endl;  // 输出行号的简单示例
#else
#define DEBUG_OUTPUT
#endif
 
#define CONST_INT(num) \
    ConstantInt::get(num, module)
 
#define CONST_FP(num) \
    ConstantFP::get(num, module) // 得到常数值的表示,方便后面多次用到
    
int main() {
  auto module = new Module("while code");
  auto builder = new IRBuilder(nullptr, module); //该类提供了独立的接口创建各种 IR 指令
  Type *Int32Type = Type::get_int32_type(module);
 
  // main函数
  auto mainFun = Function::create(FunctionType::get(Int32Type, {}),"main", module);
  auto bb = BasicBlock::create(module, "entry", mainFun); //创建BasicBlock
  builder->set_insert_point(bb);  //将当前插入指令点的位置设在bb
  
  auto aAlloca=builder->create_alloca(Int32Type); //int a;
  auto iAlloca=builder->create_alloca(Int32Type); //int i;
  
  builder->create_store(CONST_INT(10), aAlloca);  //a = 10;
  builder->create_store(CONST_INT(0), iAlloca);   //i = 0;
  
  
  auto condBB = BasicBlock::create(module, "whileBB", mainFun);  // while
  auto trueBB = BasicBlock::create(module, "trueBB", mainFun);    // true
  auto retBB = BasicBlock::create(module, "falseBB", mainFun);  // ret
  builder->create_br(condBB); 
  
  builder->set_insert_point(condBB); // condBB
  auto iLoad = builder->create_load(iAlloca);  //i
  auto cmp = builder->create_icmp_lt(iLoad, CONST_INT(10));  //i < 10
  auto br = builder->create_cond_br(cmp, trueBB, retBB);  // if(i<10)goto true else goto false
   
  builder->set_insert_point(trueBB);  // if true; 
  iLoad = builder->create_load(iAlloca);  //i
  auto add1=builder->create_iadd(iLoad,CONST_INT(1)); //i+1
  builder->create_store(add1, iAlloca); //i=i+1
  auto aLoad = builder->create_load(aAlloca);  //a
  iLoad = builder->create_load(iAlloca); //i
  auto add2=builder->create_iadd(iLoad,aLoad);//a+i
  builder->create_store(add2, aAlloca); //a = a + i;
  builder->create_br(condBB);  // br condBB
  
  builder->set_insert_point(retBB);  // ret(false)
  aLoad = builder->create_load(aAlloca);  //a
  builder->create_ret(aLoad);  //return a;
 
  std::cout << module->print();
  delete module;
  return 0;
}